<template>
    <el-form-item :label="label">
        <el-select v-model="data" @click="handleClick" remote readonly placeholder="请选择"></el-select>
    </el-form-item>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import {showMsg} from '@dashboard/utils'
const {label,url,config,origin,AccessToken,cookie} = defineProps<{
    label:string
    /**展示字段和存值字段 */
    config:{label:string,value:{[key:string]:any}|'all'|string}
    /**打开页面的域名 */
    origin:string
    /**打开的地址 */
    url:string
    /**localStorage.AccessToken*/
    AccessToken:string
    /**document.cookie*/
    cookie:string
}>()
const value = defineModel<{[key:string]:any}[]>({default:[]});
const data = computed(()=>{
    return value.value.reduce((a,b)=>a+=`${(b[config.label]?b[config.label]+'，':'')}`,'').slice(0, -1);
})
const messageEvent = {
    /**设置关闭弹窗 */
    colseMsg(){},
    /**注销监听 */
    remove(){
        window.removeEventListener("message", messageEvent.messageListener);
    },
    /**关闭弹窗 */
    colse(){
        this.colseMsg()
        this.remove()
    },
    /**添加监听 */
    add(){
        window.addEventListener('message', this.messageListener, false);
    },
    /**监听回调 */
    messageListener(event){
        if(event.data?.type=='redirected'){
            let data = event.data?.data?.data?.[0]||[];
            value.value = data.reduce((a,b)=>{
                let obj = {};
                if(config.value=='all'){
                    for(let key in b)obj[key] = b[key];
                }
                else if(typeof config.value=='string'){
                    obj[config.value] = b[config.value]
                }
                else{
                    for(let key in config.value){
                        obj[key] = b[config.value[key]]
                    }
                }
                if(!obj[config.label])obj[config.label] = b[config.label];
                return a.push(obj),a;
            },[])
            messageEvent.colse()
        }
    }
}
const handleClick = ()=>{
    messageEvent.colseMsg = showMsg({
        title:'选择页',
        url:`${origin}/Html/Redirected/index.html`,
        success:(iframe)=>{
            iframe.contentWindow!.postMessage({
                url,
                AccessToken,
                cookie
                ,onload:`(e)=>{e.target.openerWindow = e.redirected;}`
            },'*');
            // 添加监听器
            messageEvent.add()
        },
        beforeClose(){
            // 移除监听器
            messageEvent.remove()
        }
    })
}
</script>